Popular Searches
Popular Course Categories
Popular Courses

Understanding SessionFactory and Session

Understanding SessionFactory and Session

Hibernate ORM and Persistence Fundamentals

Understanding SessionFactory and Session in Hibernate

Course: Advanced Java Training

Topic: Understanding SessionFactory and Session

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to SessionFactory and Session

Hibernate is a Java Object-Relational Mapping (ORM) framework that simplifies communication between Java applications and relational databases. It maps Java objects to database tables and helps developers perform database operations without writing repetitive JDBC code for every operation.

Two important components of Hibernate are SessionFactory and Session. They work together to manage persistence operations, interact with the database, and maintain the state of Java entities.

SessionFactory is responsible for creating Hibernate Session objects and maintaining shared Hibernate services and mapping metadata. A Session represents a short-lived unit of work in which an application can save, retrieve, update, and delete persistent objects.

Understanding these components is essential when developing Java applications such as employee management systems, banking applications, e-commerce platforms, student portals, and inventory management systems.

2. Learning Objectives

  • Understand the purpose of SessionFactory and Session.
  • Learn the differences between the two components.
  • Understand how Hibernate creates and manages sessions.
  • Configure and initialize a SessionFactory.
  • Open, use, and close a Session correctly.
  • Perform CRUD operations using Hibernate.
  • Understand transactions and entity persistence states.
  • Learn about the first-level cache and session lifecycle.
  • Identify common SessionFactory and Session errors.
  • Apply lifecycle, resource-management, and performance best practices.

3. What Is SessionFactory?

SessionFactory is an interface in the org.hibernate package that represents Hibernate's configured persistence environment. It contains the runtime metadata describing entity classes, their properties, relationships, and mappings to database tables.

It acts as a factory for creating Session instances. It also provides access to shared services that may include second-level caching and integration with connection pools and transaction-management systems, depending on the application's configuration.

Key Characteristics of SessionFactory

  • Thread-safe: A SessionFactory is designed to be shared across multiple application threads.
  • Expensive to create: Initialization involves loading configuration, processing mappings, and preparing Hibernate services.
  • Long-lived: It is normally created once for a database configuration and reused throughout the application's lifetime.
  • Creates sessions: It provides methods such as openSession() to obtain Session instances.
  • Stores mapping metadata: It maintains the runtime model used to map Java entities to relational tables.
  • Supports shared services: Depending on configuration, it may manage or integrate with caches, connection providers, and transaction systems.
  • Must be closed at shutdown: Closing the factory releases its associated resources.

Simple Definition

SessionFactory is the long-lived Hibernate component that creates Session objects and maintains shared persistence infrastructure.

4. What Is Session?

Session is an interface in the org.hibernate package that provides the primary native Hibernate API for interacting with persistent entities.

A Session represents a unit of work between the Java application and the database. It allows the application to save new objects, retrieve existing entities, update managed objects, delete records, and execute Hibernate queries.

A Session also maintains a persistence context, commonly called the first-level cache, that tracks managed entities and their changes during its lifetime.

Key Characteristics of Session

  • Short-lived: A Session should normally be associated with one bounded unit of work.
  • Not thread-safe: A Session should not be shared concurrently between multiple threads.
  • Manages entity state: It tracks entities associated with its persistence context.
  • Supports database operations: It provides methods such as persist(), find(), get() in supported versions, merge(), and remove() or delete(), depending on the API and version.
  • Supports transactions: A Session can work with Hibernate transactions and the application's configured transaction-management system.
  • Maintains a first-level cache: It helps manage entity identity and reduces repeated database reads within the same persistence context.
  • Must be closed: Applications using manually opened sessions should close them when the unit of work finishes.

Simple Definition

A Session is a short-lived Hibernate object used to perform database operations and manage entities during a unit of work.

5. Difference Between SessionFactory and Session

Feature SessionFactory Session
Purpose Creates sessions and maintains shared Hibernate infrastructure. Performs persistence operations for a unit of work.
Lifecycle Long-lived. Short-lived.
Thread safety Thread-safe. Not thread-safe.
Creation cost Relatively expensive. Generally cheaper than creating a factory.
Typical quantity Usually one per database configuration in a standalone application. Created as needed for each unit of work or request.
Entity operations Does not normally perform individual entity CRUD operations directly. Provides APIs for saving, retrieving, updating, and deleting entities.
Persistence context Does not maintain the ordinary first-level persistence context for each unit of work. Maintains its own persistence context and first-level cache.
Transaction handling Provides access to configured transaction infrastructure. Can begin, commit, and roll back transactions when using resource-local transaction management.
Closing Normally closed when the application shuts down. Closed after its unit of work is complete.
API org.hibernate.SessionFactory org.hibernate.Session

6. How SessionFactory and Session Work Together

SessionFactory and Session work together to provide a structured approach to database persistence.

  1. The application loads Hibernate configuration.
  2. Hibernate initializes its mapping metadata and shared services.
  3. A SessionFactory is created.
  4. The application requests a Session from the factory.
  5. The Session begins or participates in a transaction when required.
  6. The application performs persistence operations on entities.
  7. Hibernate synchronizes changes with the database, usually during flush or transaction commit.
  8. The transaction is committed or rolled back as appropriate.
  9. The Session is closed after the unit of work finishes.
  10. The SessionFactory remains available for subsequent operations until application shutdown.

Workflow Diagram

Java Application
       |
       v
Hibernate Configuration
       |
       v
SessionFactory
       |
       +---------------------+
       |                     |
       v                     v
   Session 1              Session 2
       |                     |
       v                     v
 Persistence Context    Persistence Context
       |                     |
       v                     v
 Transactions and Database Operations
       |                     |
       +----------+----------+
                  |
                  v
            Relational Database

Each Session has its own persistence context. Sessions created from the same SessionFactory can share configured factory-level services, but their managed entity state is not automatically shared.

7. Creating a SessionFactory

In a traditional Hibernate application, a SessionFactory can be created using the Configuration class. Hibernate reads the configuration file, loads mapping information, and builds the factory.

Example: Creating a SessionFactory

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory SESSION_FACTORY =
        buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration()
                    .configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (RuntimeException exception) {
            throw new ExceptionInInitializerError(exception);
        }
    }

    public static SessionFactory getSessionFactory() {
        return SESSION_FACTORY;
    }

    public static void shutdown() {
        if (!SESSION_FACTORY.isClosed()) {
            SESSION_FACTORY.close();
        }
    }
}

Explanation

  • Configuration loads the Hibernate configuration and mapping information.
  • configure("hibernate.cfg.xml") reads the specified XML file from the classpath.
  • buildSessionFactory() initializes the factory.
  • The static field allows the application to reuse the same factory instance.
  • getSessionFactory() provides access to the initialized factory.
  • shutdown() closes the factory and releases its resources.

This utility is a simple standalone example. In a real application, ensure that initialization failures are handled appropriately and that the shutdown method is called during application termination. Framework-managed applications usually provide their own lifecycle management.

8. Understanding hibernate.cfg.xml

The hibernate.cfg.xml file is a traditional Hibernate configuration file. It typically defines the database connection properties, SQL logging options, and entity mappings.

Example Configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">
            com.mysql.cj.jdbc.Driver
        </property>

        <property name="hibernate.connection.url">
            jdbc:mysql://localhost:3306/employee_db
        </property>

        <property name="hibernate.connection.username">
            app_user
        </property>

        <property name="hibernate.connection.password">
            CHANGE_ME
        </property>

        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <mapping class="com.example.Employee"/>
    </session-factory>
</hibernate-configuration>

Replace the example credentials with secure local configuration and ensure the database and table exist. Do not commit real production passwords to source control. The JDBC driver must also be available in the project dependencies.

Common Configuration Properties

Property Purpose
hibernate.connection.driver_class Identifies the JDBC driver class.
hibernate.connection.url Specifies the database connection URL.
hibernate.connection.username Specifies the database username.
hibernate.connection.password Specifies the database password.
hibernate.show_sql Enables SQL statement output.
hibernate.format_sql Formats generated SQL for readability.
hibernate.hbm2ddl.auto Hibernate-specific schema-management setting.

For new projects, verify the configuration syntax and supported properties against the Hibernate version in use. Production schema changes should generally be managed through reviewed database migrations.

9. Opening a Session

After the SessionFactory is initialized, the application can create a Session by calling openSession().

Example

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class SessionExample {

    public static void main(String[] args) {
        SessionFactory factory =
            HibernateUtil.getSessionFactory();

        try (Session session = factory.openSession()) {
            System.out.println("Session opened successfully.");
            System.out.println("Session open: " + session.isOpen());
        }
    }
}

The try-with-resources statement closes the Session automatically when execution leaves the block. This helps prevent resource leaks.

Opening a Session does not necessarily mean that a physical database connection is acquired immediately. Depending on the configured connection provider and the operation performed, connection acquisition may be delayed until needed.

10. Session Lifecycle

A Session should have a clear beginning and end. It is commonly created at the start of a unit of work and closed after the required operations and transaction handling are complete.

Typical Session Lifecycle

  1. Creation: Obtain a Session from the SessionFactory.
  2. Transaction setup: Begin a transaction when the unit of work needs one.
  3. Entity loading: Retrieve persistent entities from the database.
  4. Entity changes: Create, modify, or remove entities.
  5. Flush: Hibernate synchronizes pending changes with the database when required.
  6. Commit or rollback: Finalize or undo the transaction.
  7. Closure: Close the Session and release its persistence context and associated resources.

Lifecycle Example

Session session = sessionFactory.openSession();

try {
    org.hibernate.Transaction transaction =
        session.beginTransaction();

    // Perform database operations here.

    transaction.commit();
} catch (RuntimeException exception) {
    // Roll back an active transaction where appropriate.
    throw exception;
} finally {
    session.close();
}

This shortened example illustrates the lifecycle only. In production code, ensure rollback is attempted when a transaction remains active after failure. Try-with-resources is generally preferred for reliably closing the Session.

11. Performing CRUD Operations Using Session

CRUD stands for Create, Read, Update, and Delete. Hibernate Session provides methods for performing these common persistence operations.

Operation Common Hibernate Method Purpose
Create persist() Makes a new entity persistent.
Read find() or get() in supported versions Retrieves an entity by its identifier.
Update Modify a managed entity Hibernate detects changes and synchronizes them.
Merge merge() Copies the state of a detached object to a managed instance.
Delete remove() or delete(), depending on API/version Marks an entity for removal.

The exact method availability and recommendations can differ between Hibernate versions. The following examples use the native Hibernate API with a modern Hibernate version.

12. Creating an Entity Class

Before performing CRUD operations, define an entity class that represents a database table.

Employee.java

package com.example;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Column;
import java.math.BigDecimal;

@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 100)
    private String name;

    @Column(nullable = false, unique = true, length = 150)
    private String email;

    @Column(nullable = false, precision = 12, scale = 2)
    private BigDecimal salary;

    public Employee() {
    }

    public Employee(String name, String email, BigDecimal salary) {
        this.name = name;
        this.email = email;
        this.salary = salary;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
}

The @Entity annotation marks the class as persistent, @Table specifies the table name, and @Id identifies the primary key. The database schema must match the mapping or be created using an appropriate schema-management process.

13. Create Operation Using Session

The persist() method makes a new entity persistent in the current Session. The SQL INSERT may be executed immediately or later during flush or transaction commit, depending on the identifier strategy and Hibernate's behavior.

Example

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.math.BigDecimal;

public class CreateEmployee {

    public static void main(String[] args) {
        SessionFactory factory =
            HibernateUtil.getSessionFactory();

        try (Session session = factory.openSession()) {
            Transaction transaction = session.beginTransaction();

            try {
                Employee employee = new Employee(
                    "Aarav Sharma",
                    "[email protected]",
                    new BigDecimal("45000.00")
                );

                session.persist(employee);

                transaction.commit();

                System.out.println("Employee saved successfully.");
                System.out.println("Employee ID: " + employee.getId());

            } catch (RuntimeException exception) {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
                throw exception;
            }
        }
    }
}

Explanation

  • The Session is opened using the SessionFactory.
  • A transaction is started before the database-changing operation.
  • A new Employee object is created.
  • session.persist(employee) makes the entity persistent.
  • transaction.commit() commits the changes.
  • The Session is automatically closed by try-with-resources.

14. Read Operation Using Session

The read operation retrieves an existing entity from the database. The native Hibernate Session API provides find() in modern Hibernate versions and supports other retrieval approaches depending on the API version.

Example

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class ReadEmployee {

    public static void main(String[] args) {
        SessionFactory factory =
            HibernateUtil.getSessionFactory();

        Long employeeId = 1L;

        try (Session session = factory.openSession()) {
            Employee employee =
                session.find(Employee.class, employeeId);

            if (employee != null) {
                System.out.println("Name: " + employee.getName());
                System.out.println("Email: " + employee.getEmail());
                System.out.println("Salary: " + employee.getSalary());
            } else {
                System.out.println("Employee not found.");
            }
        }
    }
}

The find() operation retrieves an entity by its primary key. If no entity with the specified identifier exists, it returns null. The entity may be returned from the Session's first-level cache rather than requiring a new database query.

15. Update Operation Using Session

When an entity is loaded into a Session, it becomes managed by that persistence context. Changes made to the managed entity are normally detected automatically. Hibernate synchronizes these changes with the database during flush or transaction commit.

Example

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.math.BigDecimal;

public class UpdateEmployee {

    public static void main(String[] args) {
        SessionFactory factory =
            HibernateUtil.getSessionFactory();

        Long employeeId = 1L;

        try (Session session = factory.openSession()) {
            Transaction transaction = session.beginTransaction();

            try {
                Employee employee =
                    session.find(Employee.class, employeeId);

                if (employee != null) {
                    employee.setSalary(new BigDecimal("55000.00"));
                    transaction.commit();

                    System.out.println("Employee salary updated.");
                } else {
                    transaction.rollback();
                    System.out.println("Employee not found.");
                }
            } catch (RuntimeException exception) {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
                throw exception;
            }
        }
    }
}

In this example, the entity is managed by the current Session. Hibernate detects the salary change and synchronizes it during commit. Calling an explicit update method is generally unnecessary for an already managed entity.

16. Delete Operation Using Session

The delete operation removes a persistent entity from the database. In the modern native Hibernate API, remove() can be used for a managed entity.

Example

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class DeleteEmployee {

    public static void main(String[] args) {
        SessionFactory factory =
            HibernateUtil.getSessionFactory();

        Long employeeId = 1L;

        try (Session session = factory.openSession()) {
            Transaction transaction = session.beginTransaction();

            try {
                Employee employee =
                    session.find(Employee.class, employeeId);

                if (employee != null) {
                    session.remove(employee);
                    transaction.commit();
                    System.out.println("Employee deleted.");
                } else {
                    transaction.rollback();
                    System.out.println("Employee not found.");
                }
            } catch (RuntimeException exception) {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
                throw exception;
            }
        }
    }
}

Deletion should be performed only after validating that the caller is authorized to remove the record. Database constraints and relationships may also affect whether the operation succeeds.

17. Understanding Hibernate Transactions

A transaction groups database operations into a logical unit of work. Transactions help maintain consistency when multiple related changes must succeed or fail together.

Hibernate supports transaction operations through the Transaction interface. In standalone applications using resource-local transactions, the Session can begin a transaction, commit it, or roll it back.

Common Transaction Methods

Method Purpose
beginTransaction() Begins a transaction in the configured transaction model.
commit() Commits the active transaction.
rollback() Attempts to undo the transaction's changes.
isActive() Checks whether the transaction is active.

Example Transaction Workflow

try (Session session = sessionFactory.openSession()) {
    org.hibernate.Transaction transaction =
        session.beginTransaction();

    try {
        // Perform related persistence operations.

        transaction.commit();
    } catch (RuntimeException exception) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw exception;
    }
}

A transaction should not be left open indefinitely. After a persistence failure, the application should follow the transaction-management contract and avoid continuing to use a Session that may be in an inconsistent state. In many cases, closing the Session and starting a fresh unit of work is the safest approach.

18. Understanding the First-Level Cache

Hibernate maintains a first-level cache within each Session. This cache is also known as the persistence context. It tracks managed entities and helps Hibernate maintain consistent entity identity within the unit of work.

For example, if an Employee with ID 1 is loaded twice through the same Session, Hibernate can return the same managed entity instance without executing a second database query for the same lookup, provided the entity remains in the persistence context and the relevant conditions are unchanged.

Example

try (Session session = sessionFactory.openSession()) {

    Employee first =
        session.find(Employee.class, 1L);

    Employee second =
        session.find(Employee.class, 1L);

    System.out.println(first == second);
}

When the same entity remains managed in the same Session, the identity comparison will ordinarily print true. This illustrates the persistence context's entity identity behavior.

Important Cache Points

  • The first-level cache is associated with an individual Session.
  • It is enabled by default and is not a shared application-wide cache.
  • It helps track changes to managed entities.
  • It can reduce repeated entity loads within the same persistence context.
  • It is cleared or discarded when the Session is closed.
  • It is different from the optional second-level cache associated with the SessionFactory.

19. SessionFactory and Second-Level Cache

The second-level cache is an optional caching mechanism that can share cached entity or collection data across Sessions created by the same SessionFactory, depending on the cache provider and configuration.

Unlike the first-level cache, which belongs to a single Session, the second-level cache is associated with the SessionFactory. It may reduce database reads for suitable workloads, but it requires careful configuration and cache-consistency planning.

First-Level Cache Second-Level Cache
Associated with a Session. Associated with the SessionFactory.
Enabled by default as part of the persistence context. Optional and requires suitable configuration.
Entity state is limited to one Session's persistence context. May share eligible cached data across multiple Sessions.
Exists for the Session's lifecycle. Can persist across Session lifecycles while the factory and cache are active.

Not every entity or query is automatically cached in the second-level cache. Caching behavior depends on provider settings, cache-region configuration, entity eligibility, and cache strategy.

20. Difference Between openSession() and getCurrentSession()

Hibernate provides different ways to obtain a Session. The correct approach depends on how the application manages the unit of work and transactions.

openSession() getCurrentSession()
Creates a new Session. Obtains the Session associated with the configured current-session context.
The application is generally responsible for closing it. Lifecycle is controlled by the configured context and its integration.
Useful for explicit Session lifecycle management. Useful when a framework or configured context manages the Session lifecycle.
Does not automatically imply a transaction is started. Does not itself guarantee that a transaction has been started; behavior depends on configuration and transaction management.

getCurrentSession() requires an appropriate current-session context or integration. It should not be assumed to work in every standalone application without configuration.

21. Session and EntityManager

Hibernate provides its native Session API, while Jakarta Persistence defines the standard EntityManager API. When Hibernate is used as a Jakarta Persistence provider, Session and EntityManager represent closely related persistence functionality.

Session EntityManager
Hibernate-specific API. Standard Jakarta Persistence API.
Uses org.hibernate.Session. Uses jakarta.persistence.EntityManager.
Offers Hibernate-specific operations and extensions. Provides a provider-independent persistence interface for standard operations.
Can be obtained through SessionFactory.openSession(). Can be created through an EntityManagerFactory.

Applications can choose the standard EntityManager API for portability or the native Session API when Hibernate-specific functionality is needed. Avoid mixing lifecycle and transaction assumptions from different APIs without understanding the configuration.

22. Common SessionFactory and Session Errors

Error or Problem Possible Cause Recommended Solution
SessionFactory creation fails Invalid configuration, missing dependencies, or database configuration errors. Inspect the complete exception stack and verify the configuration file and dependencies.
JDBC driver not found Missing or incorrect database driver dependency. Add the correct driver and reload the build project.
Database connection refused Database server is stopped or the host and port are incorrect. Verify database availability, network access, and connection URL.
Session is closed Code attempts to use a Session after its lifecycle has ended. Open a new Session for the next unit of work.
LazyInitializationException A lazy association is accessed after its persistence context is closed. Fetch required data within the intended unit of work or define a suitable fetch plan.
Transaction is not active Transaction was committed, rolled back, or never started. Review transaction boundaries and exception-handling logic.
Duplicate key exception Identifier or unique-column values conflict with existing data. Verify identifier generation and unique constraints.
Too many database connections Sessions, transactions, or connections are not being released correctly. Close Sessions reliably and review connection-pool configuration.
Unexpected SQL updates Managed entity state changed and was synchronized during flush. Review entity modifications and transaction boundaries.

23. Best Practices for SessionFactory and Session

  • Create the SessionFactory once per appropriate database configuration and reuse it.
  • Do not create a new SessionFactory for every database operation.
  • Use a new Session for each independent unit of work unless a framework manages the lifecycle differently.
  • Never share a Session concurrently across multiple threads.
  • Close manually opened Sessions with try-with-resources where possible.
  • Close the SessionFactory during application shutdown when your code owns its lifecycle.
  • Use transactions for database-changing operations.
  • Commit successful transactions and roll back failed transactions when appropriate.
  • Avoid holding a Session open across long-running user interactions.
  • Understand when Hibernate flushes changes to the database.
  • Use parameterized queries or safe query APIs when incorporating user input.
  • Keep database credentials secure.
  • Monitor SQL queries and investigate unnecessary database access.
  • Use suitable fetching strategies to avoid N+1 query problems.
  • Do not use automatic schema updates as a replacement for controlled production migrations.

24. Practical Project: Employee Management System

Build an Employee Management System to practice SessionFactory and Session operations.

Project Requirements

  • Create a Java Maven project.
  • Add compatible Hibernate ORM and JDBC dependencies.
  • Configure a relational database.
  • Create an Employee entity.
  • Initialize a reusable SessionFactory.
  • Open and close Sessions correctly.
  • Implement employee creation, retrieval, modification, and deletion.
  • Use transactions for changes.
  • Inspect SQL output and verify the database records.

Suggested Project Structure

hibernate-session-demo/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── example/
        │           ├── Employee.java
        │           ├── HibernateUtil.java
        │           ├── CreateEmployee.java
        │           ├── ReadEmployee.java
        │           ├── UpdateEmployee.java
        │           └── DeleteEmployee.java
        └── resources/
            └── hibernate.cfg.xml

Implementation Steps

  1. Create the database and employees table.
  2. Add the Hibernate and JDBC driver dependencies.
  3. Configure the database connection in hibernate.cfg.xml.
  4. Create the Employee entity with the required annotations.
  5. Build a reusable SessionFactory utility.
  6. Write a program that opens a Session and saves an employee.
  7. Retrieve an employee by identifier.
  8. Update the employee's salary inside a transaction.
  9. Delete a test record.
  10. Test failure scenarios and verify that resources are closed correctly.

25. Practice Exercises

  1. Define SessionFactory and explain its role in Hibernate.
  2. Define Session and describe its role in persistence operations.
  3. Write a Java utility class that creates a reusable SessionFactory.
  4. Open a Session using openSession() and close it safely.
  5. Create an Employee entity and save a new employee using persist().
  6. Retrieve an employee using find().
  7. Update a managed entity and observe the generated SQL.
  8. Delete an entity inside a transaction.
  9. Demonstrate the first-level cache by retrieving the same entity twice within one Session.
  10. Explain why SessionFactory can be shared across threads but Session should not be shared concurrently.
  11. Compare openSession() and getCurrentSession().
  12. Identify the cause of a LazyInitializationException in a sample application.

26. Interview Questions and Answers

Q1. What is SessionFactory in Hibernate?

Answer: SessionFactory is a thread-safe, long-lived Hibernate component that maintains mapping metadata and shared persistence services. It creates Session instances for application units of work.

Q2. What is Session in Hibernate?

Answer: Session is a short-lived Hibernate object used to perform persistence operations and manage entity state within a persistence context.

Q3. What is the main difference between SessionFactory and Session?

Answer: SessionFactory creates and manages shared Hibernate infrastructure, while Session performs database operations for a particular unit of work.

Q4. Is SessionFactory thread-safe?

Answer: Yes. SessionFactory is designed to be shared by multiple application threads.

Q5. Is Session thread-safe?

Answer: No. A Session should not be shared concurrently across multiple threads because it maintains mutable persistence-context state.

Q6. Why should SessionFactory usually be created only once?

Answer: Creating a SessionFactory involves expensive initialization of configuration, mappings, and shared services. Reusing a factory avoids unnecessary initialization overhead.

Q7. How do you create a SessionFactory?

Answer: In a traditional native Hibernate application, it can be created using new Configuration().configure().buildSessionFactory(), provided the configuration and dependencies are correct.

Q8. How do you open a Session?

Answer: A Session can be opened using sessionFactory.openSession().

Q9. What is the first-level cache?

Answer: The first-level cache is the persistence context associated with an individual Session. It tracks managed entities and helps maintain entity identity within that Session.

Q10. What is the difference between the first-level and second-level caches?

Answer: The first-level cache belongs to a single Session and is enabled by default. The optional second-level cache is associated with the SessionFactory and can share eligible cached data between Sessions.

Q11. What happens when a Session is closed?

Answer: The Session's persistence context is closed and its associated resources are released. Entities previously managed by it become detached, and lazy associations may no longer be initialized through that closed persistence context.

Q12. Why are transactions important in Hibernate?

Answer: Transactions group related database operations so they can be committed together or rolled back when a failure occurs.

Q13. What is the purpose of persist()?

Answer: The persist() method makes a new entity persistent in the current persistence context.

Q14. What is the difference between openSession() and getCurrentSession()?

Answer: openSession() creates a new Session whose lifecycle the caller generally manages. getCurrentSession() obtains a Session associated with the configured current-session context.

Q15. What is LazyInitializationException?

Answer: It commonly occurs when the application attempts to access a lazy association after the Session or persistence context needed to initialize it has been closed.

27. Quick Revision Checklist

  • SessionFactory is a long-lived and thread-safe component.
  • SessionFactory creates Session objects.
  • Session is a short-lived unit-of-work object.
  • Session is not thread-safe.
  • Session maintains the first-level cache or persistence context.
  • Session supports entity persistence and retrieval operations.
  • Transactions help maintain data consistency.
  • Managed entity changes are synchronized during flush or commit.
  • Manually opened Sessions should be closed reliably.
  • SessionFactory should be reused and closed when its owning application shuts down.
  • The second-level cache is optional and associated with the SessionFactory.
  • Correct fetching strategies and resource management help prevent common performance problems.

28. Conclusion

SessionFactory and Session are fundamental components of Hibernate. SessionFactory maintains the configured persistence environment and creates sessions, while Session manages entities and performs database operations during a unit of work.

By understanding their roles, lifecycles, thread-safety requirements, transaction behavior, and caching responsibilities, Java developers can build reliable applications with better resource management and maintainable database-access code.

Practice creating a SessionFactory, opening Sessions, performing CRUD operations, managing transactions, and closing resources correctly to strengthen your understanding of Hibernate persistence.

Learn More with JustAcademy

Explore the Advanced Java Training Course to continue learning Hibernate, ORM, and enterprise Java development.

Register for a Course Demo to learn more about the training, or visit the JustAcademy Official Website.

Additional Reference: Official Hibernate ORM User Guide

Previous Next
whatsapp